# coding: utf-8
# @Author : lryself
# @Date : 2020/12/18 20:19
# @Software: PyCharm
import datetime

from flask import current_app, g
from sqlalchemy import or_

from ..controller.userCollectController import UserCollectController
from ..models import db
from ..models.UserCollectModel import UserCollect
from ..utils import commons
from ..utils.response_code import RET


class UserCollectManager(UserCollectController):
    @classmethod
    def add_note(cls, **kwargs):
        kwargs['parent_id'] = kwargs.pop('parentID')
        return cls.add(**kwargs)

    @classmethod
    def get_note(cls, **kwargs):
        return cls.get(**kwargs)

    @classmethod
    def delete_note(cls, **kwargs):
        return cls.delete(**kwargs)

    @classmethod
    def delete_note_folder(cls, **kwargs):
        user_ID = kwargs.get("user_id") if kwargs.get("user_id") else g.user.user_id
        collect_ID = kwargs.get('collect_id')

        try:
            filter_list = []
            filter_list.append(cls.IsDeleted == 0)
            filter_list.append(cls.userID == user_ID)
            filter_list.append(cls.collectID == collect_ID)
            filter_list.append(cls.type == '2')

            note = db.session.query(cls).filter(*filter_list)

            if not note.first():
                return {'code': RET.NODATA, 'msg': '无用户笔记数据'}

            parent_ID = note.first().collectID

            note.update({'IsDeleted': '1'})
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，查询笔记信息失败', 'error': str(e)}

        try:
            # 队列删除法(bfs)
            back_data = []
            delete_list = []
            delete_list.append(parent_ID)

            while delete_list:

                parent_ID = delete_list.pop(0)
                filter_list = []
                filter_list.append(cls.userID == user_ID)
                filter_list.append(cls.parentID == parent_ID)

                notes = db.session.query(cls).filter(*filter_list)

                notes.update({'IsDeleted': '1'})
                db.session.commit()

                notes_data = commons.query_to_dict(notes.all())
                back_data.append(notes_data)

                for note_data in notes_data:
                    if note_data.get('type') == 2:
                        delete_list.append(note_data.get('collectID'))

        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，删除笔记信息失败', 'error': str(e)}

        return {'code': RET.OK, 'msg': '删除笔记文件夹成功', 'data': back_data}

    @classmethod
    def rename_note(cls, **kwargs):
        return cls.update(**kwargs)

    @classmethod
    def get_all_parent_ID(cls, **kwargs):
        filter_list = []
        filter_list.append(cls.IsDeleted == 0)
        filter_list.append(cls.collectID == kwargs.get('collectID'))
        filter_list.append(cls.type == 1)

        try:
            note = db.session.query(cls.parentID).filter(*filter_list)

            if not note.first():
                return {'code': RET.NODATA, 'msg': '无用户笔记数据'}

            parent_ID_list = [commons.query_to_dict(note.first())['parentID']]

            while parent_ID_list[len(parent_ID_list) - 1] != '0':
                collect_ID = parent_ID_list[len(parent_ID_list) - 1]
                filter_list = []
                filter_list.append(cls.collectID == collect_ID)
                filter_list.append(cls.type == 2)
                filter_list.append(cls.IsDeleted == 0)
                result = db.session.query(cls.parentID).filter(*filter_list)
                parent_ID_list.append(commons.query_to_dict(result.first())['parentID'])

            parent_ID_list.pop()

            return {'code': RET.OK, 'msg': '获取笔记文件夹节点列表成功', 'data': parent_ID_list}

        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，获取笔记内容失败', 'error': str(e)}

    @classmethod
    def get_note_list(cls, **kwargs):
        return cls.get(**kwargs)

    @classmethod
    def update_note(cls, **kwargs):
        return cls.update(**kwargs)
